import sys
import sympy as sp
import os
import subprocess

# Runs an HFSS simulation
def runsim(trace,width,length,delta_s,sub_material,sub_thick):
    # Current folder
    cd = os.path.dirname(os.path.realpath(__file__))
    
    # Convert the trace location to the properly formatted string.
    if trace == "top":
        trace = "Top"
    elif trace == "mid":
        trace = "Mid"
    elif trace == "bot":
        trace = "Bot"
    else:
        print("Unrecognized trace location \""+trace+"\"")
        return
    
    
    # Execute the VBScript to perform the simulation
    # Params are:
    #  1: Trace location, "Top", "Mid", or "Bot"
    #  2: Dogbone width, as measured in mm
    #  3: Dogbone length, as measured in mm
    #  4: Simulation delta_s, convergence condition for HFSS simulation.
    #  5: Directory to save results in
    #FNULL = open(os.devnull, 'w')
    subprocess.call("cscript Template.vbs "+trace+" "+str(width)+" "+str(length)+" "+str(delta_s)+" \""+sub_material+"\" "+str(sub_thick)+" \""+cd+"\"")#, stdout=FNULL, stderr=subprocess.STDOUT)
    
    # Read results from file
    results = []
    if(os.path.isfile(cd+"\\sim_results.csv")):
        with open(cd+"\\sim_results.csv", "r") as resultFile:
            header = resultFile.readline()
            
            # Do stuff with headers if we need
            
            # Read each line of the csv, each line would coorespond to a simulation. Should only have 1 line unless
            # performing an HFSS parameter sweep.
            for line in resultFile:
                # Split line on commas
                vals = line.split(',')
                
                # Group the 8 vals into 4 complex numbers (ignore first val)
                cmplxVals = [complex(float(vals[i]),float(vals[i+1])) for i in range(1,9,2)]
                
                # Create a 2x2 S Matrix from the complex numbers
                results.append({"sMat":sp.Matrix([[cmplxVals[0], cmplxVals[1]], [cmplxVals[2], cmplxVals[3]]])})
        
        # Remove old CSV
        os.remove(cd+"\\sim_results.csv")
    else:
        print("Result csv not found. Template.vbs may have crashed.");
    
    if(len(results) > 0):
    
        # read convergance from file
        if(os.path.isfile(cd+"\\convergence.conv")):
            readingTable = False
            lastLine = ""
            with open(cd+"\\convergence.conv", "r") as resultFile:
                for line in resultFile:
                    if readingTable and "|" not in line:
                        break
                        
                    elif("Converged :" in line):
                        print (line.split(":"))
                        results[0]["converged"] = line.split(":")[1].strip() == "Yes"
                        
                    elif "Pass Number|Solved Elements|Max Mag. Delta S|" in line:
                        readingTable = True
                        
                    lastLine = line
            
            results[0]["delta_s"] = lastLine.split("|")[2].strip();
            
            # Remove old CONV
            os.remove(cd+"\\convergence.conv")
    
    return results
